
import config from 'config';
import schema from "async-validator";
import { AppContext } from 'ROOT/interface/App';

import WatchEntity from './watch.entity';
import WatchEntityService from './watch.service';
import { traderRobot } from 'ROOT/TraderRobot';
import KLineHistoryService from '../kline-history/KLineHistory.service';
import SymbolOrderConfigService from '../symbol-order-config/SymbolOrderConfig.service';
import { getInterval } from 'ROOT/utils';
import strategyService from '../strategy/strategy.service';

/**
 * 查询单个或者多个
 */
export const get = async (ctx: AppContext) => {
  const { id } = ctx.request.query;
  try {
    let res: WatchEntity | WatchEntity[] | undefined;
    if (id) {
      res = await WatchEntityService.findOne({ id: Number(id) });
      if (!res) {
        ctx.sendError({ message: 'error' });
        return;
      }
      ctx.sendSuccess({
        data: res
      });
    } else {
      res = await WatchEntityService.find({});
      ctx.sendSuccess({ data: res });
    }
  } catch (error) {
    ctx.sendError({ message: error });
  }
}

/**
 * 更新或者新建
 */
export const updateOne = async (ctx: AppContext) => {
  const data = ctx.request.body as Record<string, any>;

  const validator = new schema({
    id: {
      type: 'number',
      required: false
    },
    strategy_id: {
      type: 'number',
      // required: true,
    }
  });
  try {
    await validator.validate(data);
  } catch ({ errors, fields }) {
    ctx.sendError({ errors, message: errors[0] ? errors[0].message : undefined });
    return;
  }
  const userId = ctx.state.user.id;
  try {
    if (data.id) {
      const target = await WatchEntityService.findOne({id: Number(data.id)});
      const result = await WatchEntityService.updateOne(Number(data.id), data);
      if (data.strategy) {
        traderRobot.trader.udpateCustomStrategy(target.strategy.id, target.symbol, {
          code: data.strategy.strategy,
        });
      } else if (target.enable !== data.enable) {
        if (!data.enable) {
          traderRobot.removeSymbol(target.symbol);
        } else {
          traderRobot.addSymbol(target.symbol);
        }
      }
      return ctx.sendSuccess({
        data: result
      });
    } else if (data.symbol) {
      const result = await WatchEntityService.create(data);
      const [start, end ] = getInterval('1d', 120);
      const history = await KLineHistoryService.find({ symbol: data.symbol, start, end });
      await traderRobot.addSymbol(data.symbol, history.length < 120 ? true : false);
      return ctx.sendSuccess({
        data: result
      });
    }
  } catch (error) {
    ctx.sendError({ message: error.message });
  }
}


/**
 * 删除单个
 */
export const removeOne = async (ctx: AppContext) => {
  const data = ctx.request.body as Record<string, any>;
  const id = data.id;
  if (!id) {
    ctx.sendError({ message: 'id 不存在' });
    return;
  }
  try {
    const target = await WatchEntityService.findOne({id: id});
    const orderConfig = await SymbolOrderConfigService.findOne({symbol: target.symbol});
    if (orderConfig) {
      return ctx.sendError({ message: `存在引用 ${orderConfig.symbol} userid: ${orderConfig.userid}` });
    }
    const res = await WatchEntityService.deleteOne(Number(id));
    await traderRobot.removeSymbol(res.symbol);
    ctx.sendSuccess({
      data: res
    });
  } catch (error) {
    ctx.sendError({ message: error });
  }
}

export const bindStrategy = async (ctx: AppContext) => {
  const data = ctx.request.body as Record<string, any>;
  const id = data.id;
  if (!id) {
    ctx.sendError({ message: 'id 不存在' });
    return;
  }
  try {
    const target = await WatchEntityService.bindStrategy(data.id, data.strategyId);
    traderRobot.trader.udpateCustomStrategy(data.strategyId, target.symbol, {
      code: target.strategy.strategy,
    });
    ctx.sendSuccess({
      data: target
    });
  } catch (error) {
    ctx.sendError({ message: error });
  }
}


